package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号是否合规
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.不合规直接返回 错误信息
            return Result.fail("手机号错误");
        }
        //3.如果合规生成验证码
        String code = RandomUtil.randomNumbers(4);
        //4.将验证码保存到session中
        session.setAttribute("code",code);
        //5.发送验证码
        log.info("code: {}",code);
        //返回ok
        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号的格式
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.不一致直接报错
            return Result.fail("手机号错误");
        }
        //3.比较验证码
        Object cacheCode = session.getAttribute("code");
        String code = loginForm.getCode();
        if(session==null || !cacheCode.toString().equals(code)){
            //4.不一致直接报错
            return Result.fail("错误信息");
        }
        //5.根据手机号查询用户
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getPhone,loginForm.getPhone());
        User user = this.getOne(query);
        if(user==null){
            //6.不存在直接创建新用户保存到数据库中
            user=createUserWithPhone(loginForm.getPhone());
        }
        //7.最终将用户信息保存到session中  保护用户的隐私
        session.setAttribute("user", BeanUtil.copyProperties(user,UserDTO.class));
        return Result.ok();
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(6));
        this.save(user);
        return user;

    }
}
